package org.zebra.logging.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.cron.Scheduler;
import cn.hutool.cron.pattern.CronPattern;
import cn.hutool.extra.spring.SpringUtil;
import org.zebra.logging.task.LogScheduleTask;

/**
 * @author 张红彬
 */
public final class LogScheduleUtil {

    private LogScheduleUtil() {}

    private static Scheduler scheduler = null;

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                if (scheduler == null) return;
                scheduler.stop(true);
            } catch (Exception e) {
            }
        }));
    }

    public static synchronized void start() {
        if (scheduler == null) {
            scheduler = new Scheduler();
        }
        if (scheduler.isStarted()) return;
        String pattern =
                SpringUtil.getApplicationContext().getEnvironment().getProperty("zebra.log.cron", "0 0 2 1 * ?");
        scheduler.schedule("log-" + DateUtil.now(), new CronPattern(pattern), new LogScheduleTask());
    }

    public static synchronized void stop() {
        if (scheduler == null) return;
        try {
            scheduler.stop(true);
        } catch (Exception e) {
        }
    }
}
